package com.hotpot.common.config.system;

import com.hotpot.telecom.entity.BaseXid;
import com.hotpot.telecom.entity.TeleComGardenInfo;
import com.hotpot.telecom.entity.XidLocation;
import com.hotpot.telecom.utils.TeleComUtil;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.json.JSONArray;
import com.xiaoleilu.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Future;
/**
 * 描述:线程执行任务类
 * @author:ruikanwang
 * @date: 2018/1/4 0004
 * 注意：本内容仅限于新疆感知科技有限公司内部传阅,禁止外泄以及用于其他的商业目
 * Copyright © 2017-ganinfo. All rights reserved.
 */
@Service
public class AsyncTaskService {

    @Autowired
    private MongoTemplate mongoTemplate;

    Random random = new Random();// 默认构造方法

    /**
     * 表明是异步方法 无返回值
     */
    @Async
    public void executeAsyncTask(String msg) {
        System.out.println(Thread.currentThread().getName()+"开启新线程执行" + msg);
    }

    /**
     * 异常调用返回Future
     *
     * @param i
     * @return
     * @throws InterruptedException
     */
    @Async
    public Future<String> asyncInvokeReturnFuture(int i) throws InterruptedException {
        System.out.println("input is " + i);
        Thread.sleep(1000 * random.nextInt(i));
        // Future接收返回值，这里是String类型，可以指明其他类型
        Future<String> future = new AsyncResult<String>("success:" + i);
        return future;
    }

    /**
     * 异步调用存储数据
     */
    @Async
    public void addXid(TeleComGardenInfo teleComGardenInfo){
        String getalluserarea = TeleComUtil.getalluserarea(teleComGardenInfo.getCustid());
        //证明返回0
        if(!"0".equals(getalluserarea.replaceAll("\r|\n", ""))) {
            JSONArray parseArray = JSONUtil.parseArray(getalluserarea);
            for (Object object : parseArray) {
                String valueOf = String.valueOf(object);
                String[] dataArray = valueOf.split("|");
                String newData = "";
                for (String string : dataArray) {
                    if ("|".equals(string)) {
                        newData += ",";
                    } else {
                        newData += string;
                    }
                }
                String[] split = newData.split(",");
                //用户实体
                BaseXid xidEntity=new BaseXid();
                //位置实体
                XidLocation xidLocation=new XidLocation();

                Criteria criteria = Criteria.where("xId").is(split[0]).and("collectionTime").is(split[4]);
                Query query = new Query();
                query.addCriteria(criteria);
                List<BaseXid> xidEntitylist=mongoTemplate.find(query,BaseXid.class);
                if(xidEntitylist==null || xidEntitylist.size()==0){
                    xidLocation.setxId(split[0]);
                    xidEntity.setId(split[0]);
                    xidEntity.setPhone(split[1]);
                    xidEntity.setQuCode(split[2]);
                    xidEntity.setCityName(TeleComUtil.decode(split[3]));
                    xidLocation.setCollectionTime(DateUtil.parse(split[4],"yyyyMMddHHmmss").getTime());
                    xidLocation.setLon(split[5]);
                    xidLocation.setLat(split[6]);
                    //查询历史位置存储
                    getHisLocation(xidEntity,1);

                }
            }
        }
    }

    /**
     * 获取历史位置
     */
    @Async
    public void getHisLocation(BaseXid xidEntity,int type){
        //位置实体
        XidLocation xidLocation=new XidLocation();
        String endTime=DateUtil.format(new Date(),"yyyyMMddHHmmss");
        String startTime=DateUtil.format(DateUtil.offsetMinute(new Date(),-20),"yyyyMMddHHmmss");
        if(type==2){
            startTime=DateUtil.format(DateUtil.offsetDay(new Date(),-1),"yyyyMMddHHmmss");
        }
        JSONArray parseArray = JSONUtil.parseArray(TeleComUtil.getlochis(xidEntity.getId(),startTime,endTime));
        for (Object object : parseArray) {
            JSONArray jsonArray=(JSONArray)object;
            Criteria criteria = Criteria.where("xId").is(xidEntity.getId()).and("collectionTime").is(DateUtil.parse((String)jsonArray.get(2),"yyyyMMddHHmmss").getTime());
            Query query = new Query();
            query.addCriteria(criteria);
            List<XidLocation> xidLocationlist=mongoTemplate.find(query,XidLocation.class);
            if(xidLocationlist==null || xidLocationlist.size()==0){
                xidLocation.setxId(xidEntity.getId());
                xidLocation.setLon((String)jsonArray.get(0));
                xidLocation.setLat((String)jsonArray.get(1));
                xidLocation.setCollectionTime(DateUtil.parse((String)jsonArray.get(2),"yyyyMMddHHmmss").getTime());
                mongoTemplate.save(xidLocation);
            }
        }
        //更新xid最后更新时间
        xidEntity.setUpdateTime(DateUtil.current(false));
        mongoTemplate.save(xidEntity);

    }


}